package com.users.service;

import cn.xuyanwu.spring.file.storage.FileInfo;
import cn.xuyanwu.spring.file.storage.FileStorageService;

import com.common.service.AbstractTypedService;
import com.users.dao.UserDao;

import com.users.entities.User;
import com.users.vo.Register;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;


import java.util.List;

/**
 * @author fu
 */
@Component
@Slf4j
public class UserServiceImpl extends AbstractTypedService<User,Long> {
    UserDao userDao;
    @Resource
    FileStorageService fileStorageService ;

    UserServiceImpl( UserDao dao){
        this.userDao =dao;
        this.dataContext=dao;
    }

    public User getUserById(Long id) {
        if (id == null || id <= 0) {
            return null;
        }
        return userDao.findById(id).orElse(null);
    }

    /**
     * @return User
     */
    public User getUserByUserName(String userName) {

        return this.userDao.findUserByUsername(userName);
    }
//    public User loginCheck(String name,String password){
//        return userDao.findUserByUsernameAndPassword(name,password);
//    }
    public Boolean updatePassword(Long id,String password){
        int flag=0;
        flag= userDao.updatePasswordById(id, password);
        log.info(String.valueOf(flag));
        return flag == 1;

    }
    public String setImgByUserId(Long id, MultipartFile file){

        FileInfo upload = fileStorageService.of(file).upload();
        Integer integer = userDao.updateImgByUserId(upload.getUrl(),id);
        log.info(integer+"用户");
        if(integer == 0){
            boolean delete=fileStorageService.delete(upload);
            log.info("删除图片情况"+delete);
            return "false";
        }
        return "true";
    }

    public User register( Register register ){
        List<User> userList=userDao.findAll();
        User user=User.builder()
                .password(register.getPassword())
                .username(register.getUsername())
                .id((long) (userList.size()+1))
                .build();
        return userDao.save(user);
    }
}
